#coding=utf-8
#auth:beck shen
#date:2017-10-18


from pytw.core.tasklet import Tasklet
from pytw.tools import log
from pytw.core.main import MainLoop

import os
import signal


class Application(object):

    """
    应用程序对象
    appid:应用程序唯一id
    """

    def initialize(self):
        pass

    def after_initialize(self):
        pass

    def _signal_USR1(self, signum, sigfram):
        """
        信号终止进程
        """
        self._stop('receive signal USR1 stop!')

    def _stop(self, reason = 'stop success!'):
        log.err("stop_by_reason===>:", reason)
        try:
            self.stop()
            reactor.stop()
        except:
            pass
        pid = os.getpid()
        os.kill(pid, signal.SIGKILL)

    def stop(self):
        """
        子类能继承重写此方法
        """
        pass

    def _start(self):
        try:
            #初始化
            self.initialize()
            #初始化之后
            self.after_initialize()
            #注册新号函数
            signal.signal(signal.SIGUSR1, self._signal_USR1)
        except Exception as e:
            log.err("start_error===>:", e.message)                        

    def start(self):
        Tasklet.create(self._start)
        MainLoop.run()
